package com.jxl.controller;

import com.jxl.pojo.User;
import com.jxl.service.UserService;
import com.jxl.web.constant.Constant;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户控制器
 * @author 江雪林
 * @create 2021-03-29
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String userLogin(@RequestParam("username")String username,
                            @RequestParam("password")String password,
                            HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if((!"".equals(username)) && (!"".equals(password))){
            boolean result = userService.login(req,resp, username, password);
            if(result){
                return "redirect:/main";
            }
        }
        return "redirect:/login";
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session){
        session.removeAttribute(Constant.SESSION_USER);
        session.invalidate();
        return "redirect:/login";
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String register(HttpServletResponse resp,User user) throws IOException {
        if(user != null && user.getPassword() !="" & user.getUsername() != ""){
            if(userService.register(resp,user)){
                return "redirect:/login";
            }
        }
        return "redirect:/register";
    }
}
